#include "admin.h"
#include "ui_admin.h"
#include "../utility/connector.h"
#include "../data/evaluation.h"
#include <QElapsedTimer>
#include <QTimer>

Admin::Admin(QWidget *parent, Connector *connector, Evaluation *evaluation) :
    QWidget(parent),connector(connector),evaluation(evaluation),
    ui(new Ui::Admin) {
    qDebug()<<"Admin::Admin called.";
    ui->setupUi(this);
    ui->tableWidget_evaluation->clearContents();
    ui->tableWidget_evaluation->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    connect(ui->commandLinkButton_train,SIGNAL(clicked()),
            this,SLOT(train()));
    qDebug()<<"Admin::Admin returned.";
}

Admin::~Admin() {
    qDebug()<<"Admin::~Admin called.";
    delete ui;
    qDebug()<<"Admin::~Admin returned.";
}

void Admin::train() {
    qDebug()<<"Admin::train called.";
    if(evaluation->score==nullptr)
        evaluation->score=new QVector<QVector<double>>;
    duration=0;
    ui->label_duration->setText("0");
    QElapsedTimer eTimer;
    eTimer.start();
    QTimer timer;
    connect(&timer, SIGNAL(timeout()), this, SLOT(updateDuration()));
    timer.start(1000);
    connector->train(evaluation);
    duration=eTimer.elapsed()/1e3;
    timer.stop();
    push();
    qDebug()<<"Admin::train returned.";
}

void Admin::push() {
    qDebug()<<"Admin::push called.";
    ui->tableWidget_evaluation->clearContents();
    if(evaluation->score->isEmpty()) {
        return;
    }
    /* TODO: [Done] 数据上屏
     * 数据：evaluation
     */
    QString str;
    for(int i=0; i<evaluation->score->size(); i++) {
        for(int j=0; j<evaluation->score->at(i).size(); j++) {
            str=QString::number((*evaluation->score)[i][j],'E',8);
            ui->tableWidget_evaluation->setItem(j,i,new QTableWidgetItem(str));
        }
    }
    qDebug()<<"Admin::push returned.";
}

void Admin::updateDuration() {
    duration++;
    ui->label_duration->setText(QString::number(duration));
}
